<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: 100%; overflow: auto; padding-bottom: 53px"
  >
    <template slot="title">
      <div style="width: 100%">
        <span>{{ title }}</span>
        <span style="display: inline-block; width: calc(100% - 51px); padding-right: 10px; text-align: right">
          <a-button @click="toggleScreen" icon="appstore" style="height: 20px; width: 20px; border: 0px"></a-button>
        </span>
      </div>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item v-if="isAdd" label="机构" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <j-select-depart
            style="width: 100%"
            v-model="orgCode"
            :trigger-change="true"
            customReturnField="orgCode"
            :multi="false"
          ></j-select-depart>
        </a-form-model-item>
        <a-form-model-item v-if="isAdd" label="选择成员" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            placeholder="请选择成员"
            style="width: 100%"
            :allowClear="true"
            v-model="doctorId"
            @change="handleSelect"
          >
            <a-select-option v-for="item in flupDoctorsList" :value="item.dataId" :key="item.doctorId"
              >{{ item.doctorsName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="doctorName">
          <label class="required" slot="label">姓名</label>
          <a-auto-complete
            v-model="model.doctorName"
            style="width: 100%"
            placeholder="请输入姓名"
            @search="value => handleSearch(value, 'name')"
            @select="handleSearchSelect"
          >
            <template slot="dataSource">
              <a-select-option
                :name="doctor.doctorsName"
                :mobile="doctor.doctorsMobile"
                :doctorType="doctor.doctorsType"
                :value="doctor.doctorsName"
                v-for="doctor in doctorList"
                :key="doctor.doctorsName + doctor.dataId"
                >{{ doctor.doctorsName }} - {{ doctor.doctorsMobile }}</a-select-option
              >
            </template>
          </a-auto-complete>

          <!-- <a-input style="width: 100%" placeholder="请输入姓名" :max-length="10" v-model="model.doctorName" /> -->
        </a-form-model-item>

        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="doctorPhone">
          <label class="required" slot="label">手机号</label>
          <a-auto-complete
            v-model="model.doctorPhone"
            style="width: 100%"
            placeholder="请输入手机号"
            @search="value => handleSearch(value, 'mobile')"
            @select="handleSearchSelect"
          >
            <template slot="dataSource">
              <a-select-option
                :name="doctor.doctorsName"
                :mobile="doctor.doctorsMobile"
                :doctorType="doctor.doctorsType"
                :value="doctor.doctorsMobile"
                v-for="doctor in doctorList"
                :key="doctor.doctorsMobile + doctor.dataId"
                >{{ doctor.doctorsMobile }} - {{ doctor.doctorsName }}</a-select-option
              >
            </template>
          </a-auto-complete>
          <!-- <a-input style="width: 100%" placeholder="请输入手机号" v-model="model.doctorPhone" /> -->
        </a-form-model-item>

        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="doctorType">
          <label class="required" slot="label">角色</label>
          <a-select
            v-model="model.doctorType"
            placeholder="请选择角色"
            :getPopupContainer="target => target.parentNode"
            @change="$forceUpdate()"
          >
            <a-select-option disabled :value="0">请选择</a-select-option>
            <a-select-option :value="1">医助</a-select-option>
            <a-select-option :value="2">营养师</a-select-option>
            <a-select-option :value="3">健康管理师</a-select-option>
            <a-select-option :value="4">心理咨询师</a-select-option>
            <a-select-option :value="5">运动康复师</a-select-option>
            <a-select-option :value="6">责任医生</a-select-option>
            <a-select-option :value="7">主任医生</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-spin>

    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-popconfirm title="确定放弃编辑？" @confirm="handleCancel" okText="确定" cancelText="取消">
        <a-button style="margin-right: 0.8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading">提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
import { postAction } from '@/api/manage'

export default {
  name: 'TeamDoctorModal',
  components: {},
  data() {
    return {
      drawerWidth: 700,
      disableSubmit: false,
      title: '操作',
      visible: false,
      model: {},
      orgCode: '',
      doctorId: undefined,
      flupDoctorsList: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      uploadLoading: false,
      confirmLoading: false,
      validatorRules: {
        doctorName: [{ validator: this.hasName }],
        doctorPhone: [{ validator: this.isRightMobileNumber }],
        doctorType: [{ validator: this.hasRole }]
      },
      isAdd: false,
      doctorList: []
    }
  },
  watch: {
    orgCode: function(value) {
      if (value) {
        this.getFlupDoctorsList()
      }
    }
  },
  created() {},
  methods: {
    handleSearch(value, type) {
      if (value) {
        let query = { isDoctorAssistant: true }
        if (type == 'name') {
          query = Object.assign(query, { doctorsName: value })
        } else {
          query = Object.assign(query, { doctorsMobile: value })
        }

        postAction('201/02/2010213', query).then(res => {
          if (res.success) {
            console.log(res)
            this.doctorList = res.result.records
          }
        })
      }
    },
    handleSearchSelect(value, option) {
      console.log(option.data.attrs.mobile)
      this.model.doctorPhone = option.data.attrs.mobile
      this.model.doctorName = option.data.attrs.name
      this.model.doctorType = option.data.attrs.doctorType
      this.doctorList = []
      console.log(this.model.doctorPhone)
    },
    onDateChange(date, dateString) {
      this.model.time = dateString
    },
    add(record) {
      this.isAdd = true
      this.model = Object.assign({}, record)
      this.visible = true
      this.resetScreenSize()
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true
      this.resetScreenSize()
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth
      } else {
        this.drawerWidth = 700
      }
    },
    //窗口最大化切换
    toggleScreen() {
      if (this.modaltoggleFlag) {
        this.modalWidth = window.innerWidth
      } else {
        this.modalWidth = 800
      }
      this.modaltoggleFlag = !this.modaltoggleFlag
    },
    handleSelect(item) {
      console.log(item, this.flupDoctorsList)
      this.flupDoctorsList.forEach(v => {
        if (v.dataId == item) {
          this.model.doctorPhone = v.doctorsMobile
          this.model.doctorName = v.doctorsName
          this.model.doctorType = v.doctorsType
          // this.$refs.form.setFieldsValue({ doctorPhone: v.doctorsMobile })
          // this.$refs.form.setFieldsValue({ doctorName: v.doctorName })
          // this.$refs.form.setFieldsValue({ doctorType: v.doctorsType })
        }
      })
    },
    getFlupDoctorsList() {
      postAction('/doctor/list', { orgCode: this.orgCode }).then(res => {
        if (res.success) {
          this.flupDoctorsList = res.result
        }
      })
    },
    handleSubmit() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.model.doctorType == 0) {
            that.$message.warning('请选择角色')
            return
          }
          that.confirmLoading = true
          let queryData = JSON.parse(JSON.stringify(this.model))

          if (this.isAdd) {
            postAction('201/03/2010302', queryData)
              .then(res => {
                if (res.success) {
                  that.$message.success('操作成功')
                  this.$emit('ok')
                } else {
                  that.$message.error(res.message)
                }
              })
              .finally(_ => {
                this.isAdd = false
                this.handleCancel()
              })
          } else {
            postAction('201/03/2010307', queryData)
              .then(res => {
                if (res.success) {
                  that.$message.success('操作成功')
                  this.$emit('ok')
                } else {
                  that.$message.error(res.message)
                }
              })
              .finally(_ => {
                this.handleCancel()
              })
          }
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.confirmLoading = false
      this.visible = false
      this.disableSubmit = false
      this.isAdd = false
      this.orgCode = ''
      this.doctorId = ''
      this.$refs.form.resetFields()
    },
    isRightMobileNumber(rule, value, callback) {
      if (typeof this.model.doctorPhone === 'undefined' || this.model.doctorPhone === '') {
        callback(new Error('请输入手机号'))
      } else {
        const regex = /^1[3456789]\d{9}$/
        if (!regex.test(this.model.doctorPhone)) {
          callback(new Error('请输入正确手机格式'))
        }
        callback()
      }
    },
    hasName(rule, value, callback) {
      console.log(value, 'name')
      if (typeof this.model.doctorName === 'undefined' || this.model.doctorName === '') {
        callback(new Error('请输入姓名'))
      } else {
        callback()
      }
    },
    hasRole(rule, value, callback) {
      if (typeof this.model.doctorType === 'undefined' || this.model.doctorType === '') {
        callback(new Error('请选择角色'))
      } else {
        callback()
      }
    }
  }
}
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 104px;
  height: 104px;
}
.ant-upload-select-picture-card i {
  font-size: 49px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

.drawer-bootom-button {
  position: absolute;
  bottom: -8px;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
.required::before {
  display: inline-block;
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}
</style>

